package com.itbaizhan.feedback.service.impl;

import com.itbaizhan.common.vo.HasMoreResult;
import com.itbaizhan.common.vo.LivegoodsResult;
import com.itbaizhan.feedback.mapper.FeedbackMapper;
import com.itbaizhan.feedback.service.FeedbackService;
import com.itbaizhan.order.service.OrderService;
import com.itbaizhan.pojo.Feedback;
import com.itbaizhan.pojo.Order;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 评论服务 业务层
 */
@DubboService
public class FeedbackServiceImpl implements FeedbackService {

    @Autowired
    private FeedbackMapper feedbackMapper;
    /**
     * 分页查询房屋评论
     * @param id 房屋id
     * @param page 当前页码
     * @param pageSize 每页显示条数
     * @return 查询结果
     */
    @Override
    public LivegoodsResult showComment(Long id, Integer page, Integer pageSize) {
        List<Feedback> feedbackList = feedbackMapper.getFeedbackById(id, page*pageSize, pageSize);
        //敏感数据脱敏
        feedbackList.forEach(feedback -> {
            String username = feedback.getUsername().replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2");
            feedback.setUsername(username);
        });
        // 分装为VO
        HasMoreResult hasMoreResult = new HasMoreResult();
        hasMoreResult.setContents(feedbackList);
        //判断是否还有下一页
        //评论总条数
        Integer count = feedbackMapper.getFeedbackCountById(id);
        //总页数
        Integer totalPage = count%pageSize==0?count/pageSize:count/pageSize+1;
        if(page+1<totalPage){ //还有下一页
            hasMoreResult.setHasMore(true);
        }else {
            hasMoreResult.setHasMore(false);
        }
        return LivegoodsResult.ok(hasMoreResult);
    }

    @DubboReference
    private OrderService orderService;

    @GlobalTransactional
    @Transactional
    @Override
    public LivegoodsResult addFeedback(Long orderId, String feedback, Integer star) {
        Feedback feedback1 = new Feedback();
        feedback1.setOrderId(orderId);
        feedback1.setComment(feedback);
        feedback1.setStar(star);
        LivegoodsResult result = orderService.selectOrder(orderId);
        Order order = (Order) result.getData();
        feedback1.setUsername(order.getUserPhone());
        feedback1.setHouseId(order.getHouseId());
        Integer i = feedbackMapper.insertFeedback(feedback1);
        if (i==1){
            orderService.updateOrder(orderId,2);
            return LivegoodsResult.ok(feedback1);
        }
        return LivegoodsResult.error();
    }
}
